from .models import Menu
from sysmanage.models import User, Browse_record, Online, Role
from django.shortcuts import *
from django.http import JsonResponse
from django.db.models import Q, Avg, Max, Min, Count, Sum
from django.views.decorators.csrf import csrf_exempt
from loginmanage.util import *  # 自定义工具类
from django.db import connection


# 首页模版
@csrf_exempt
def index(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        return render(request, "index.html", {'ff_path': ff_path, 'path': path,
                                              'homepage': Menu.objects.filter(name="首页", parent__isnull=True),
                                              'leftmenu': Menu.objects.filter(parent__isnull=False, is_active=1),
                                              'topmenu': Menu.objects.filter(~Q(name="首页"), parent__isnull=True),
                                              })
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 菜单列表页
@csrf_exempt
def menu_page(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        return render(request, "menu/menu_list.html", {'ff_path': ff_path, 'path': path, })
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 菜单数据
@csrf_exempt
def menu_data(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        print(request.GET.get('table_name'))
        munu_list = {}
        munu_list['code'] = 0
        munu_list['msg'] = ''
        munu_list['count'] = 1000
        munu_list['data'] = list(Menu.objects.filter(is_active=1).values())
        return JsonResponse(munu_list)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 用户列表页
@csrf_exempt
def user_page(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        return render(request, "user/user_list.html", {'ff_path': ff_path, 'path': path, })
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 用户数据
@csrf_exempt
def user_data(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        user_list = {}
        user_list['code'] = 0
        user_list['msg'] = ''
        user_list['count'] = 1000
        user_list['data'] = list(User.objects.filter(is_active=1).values())
        return JsonResponse(user_list)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 历史记录
@csrf_exempt
def add_browse_record(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        menu_id = request.GET.get('id')
        response_data = {"info": "已添加"}
        if Browse_record.objects.filter(user_id=user_id).count() >= 8:  # 当前登录用书浏览记录大于等于6条时
            deletelist = Browse_record.objects.get(user_id=user_id, createby=Min('createby')).createby  # 当前用户最早时间浏览记录
            Browse_record.objects.filter(user_id=user_id, createby=deletelist).delete()  # 删除当前用户最早时间浏览记录
            Browse_record.objects.create(user_id=user_id, menu_id=menu_id)  # 创建当前浏览数据
        else:
            Browse_record.objects.create(user_id=user_id, menu_id=menu_id)  # 创建当前浏览数据
        return JsonResponse(response_data)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 查询历史记录
@csrf_exempt
def select_browse_record(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        user_id = request.COOKIES.get('user_id')
        menu_record_list = {}
        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT distinct menu.* FROM  sys_browse_record re left join sys_menu menu on re.menu_id=menu.id WHERE re.user_id = %s  order by re.createby desc",
                [user_id])
            menu_record_list['menu'] = dictfetchall(cursor)
        return JsonResponse(menu_record_list)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


@csrf_exempt
def test(request):
    role_id = 1
    path = request.scheme + "://" + request.get_host()  # url
    ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
    rolerights = '`a.role_create_rights`'
    online_list = {}
    online_list['code'] = 0
    online_list['msg'] = ''
    online_list['count'] = 1000
    online_list['data'] = ''
    return JsonResponse(online_list)
    return render(request, "test.html", {'ff_path': ff_path, 'path': path, })


# 在线数据
@csrf_exempt
def online_data(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        online_list = {}
        online_list['code'] = 0
        online_list['msg'] = ''
        online_list['count'] = 1000
        online_list['data'] = ''
        with connection.cursor() as cursor:
            cursor.execute(
                "select o.online_id,o.online_date,u.username,role_id from sys_online o left join sys_user u on o.user_id = u.user_id where o.user_id= %s",
                [user_id])
            online_list['data'] = dictfetchall(cursor)
        return JsonResponse(online_list)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 在线页面
@csrf_exempt
def online_page(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        return render(request, "online/online_list.html", {'ff_path': ff_path, 'path': path, })
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 角色列表页
@csrf_exempt
def role_page(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        return render(request, "role/role_list.html", {'ff_path': ff_path, 'path': path, })
    else:
        Role.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 角色数据
@csrf_exempt
def role_data(request):
    user_id = request.COOKIES.get('user_id')
    if check_session(request):
        role_list = {}
        role_list['code'] = 0
        role_list['msg'] = ''
        role_list['count'] = 1000
        role_list['data'] = ''
        with connection.cursor() as cursor:
            cursor.execute(
                "select * from sys_role r where 1=1 and r.is_active ='1'",
            )
            role_list['data'] = dictfetchall(cursor)
        return JsonResponse(role_list)
    else:
        Online.objects.filter(user_id=user_id).delete()  # 删除当前用户上线记录
        response = HttpResponseRedirect('/login')
        return response


# 菜单管理树
@csrf_exempt
def menu_manage_page(request):
    role_id = request.GET.get('role_id')  # 点击的角色

    if request.method == 'GET':
        layEvent = request.GET.get('layEvent')  # 点击的按钮
        role = Role.objects.get(role_id=role_id)  # 获取点击角色的数据库信息
        rolerights = ''
        if 'role_create_rights' == layEvent:
            rolerights = role.role_create_rights
        elif 'role_delete_rights' == layEvent:
            rolerights = role.role_delete_rights
        elif 'role_update_rights' == layEvent:
            rolerights = role.role_update_rights
        elif 'role_select_rights' == layEvent:
            rolerights = role.role_select_rights
        elif 'role_menu_rights' == layEvent:
            rolerights = role.role_menu_rights
        path = request.scheme + "://" + request.get_host()  # url
        ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
        menu_list = {}
        menu_list['all'] = ''

        with connection.cursor() as cursor:
            cursor.execute(
                "select id,case when parent_id is null then 0 else parent_id end as parent_id,name,case when id in(" + rolerights + ") then 'true' else 'false' end as checked from sys_menu r where 1=1 and r.is_active ='1'"
            )
            menu_list['all'] = dictfetchall(cursor)
        return render(request, "menu/menu_manage_page.html",
                      {'ff_path': ff_path, 'path': path, 'menu_list_all': menu_list['all'], 'role_id': role_id,
                       'layEvent': layEvent})
    else:
        role_id = request.POST.get('role_id')  # 点击的角色
        layEvent = request.POST.get('layEvent')  # 点击的按钮
        ids = request.POST.get('ids')  # 点击的角色
        print(role_id, layEvent, ids)

        response_data = ''
        if 'role_create_rights' == layEvent:
            Role.objects.filter(role_id=role_id).update(role_create_rights=ids)
            response_data = {"info": "成功更新角色添加按钮"}
        elif 'role_delete_rights' == layEvent:
            Role.objects.filter(role_id=role_id).update(role_delete_rights=ids)
            response_data = {"info": "成功更新角色删除按钮"}
        elif 'role_update_rights' == layEvent:
            Role.objects.filter(role_id=role_id).update(role_update_rights=ids)
            response_data = {"info": "成功更新角色编辑按钮"}
        elif 'role_select_rights' == layEvent:
            Role.objects.filter(role_id=role_id).update(role_select_rights=ids)
            response_data = {"info": "成功更新角色查看按钮"}
        elif 'role_menu_rights' == layEvent:
            Role.objects.filter(role_id=role_id).update(role_menu_rights=ids)
            response_data = {"info": "成功更新角色菜单可查看权限"}
        return JsonResponse(response_data)

# from entmanage.models import *
# from django.shortcuts import render
# from django.views.decorators.csrf import csrf_exempt
# from django.http import JsonResponse
# from django.core.validators import validate_email
# from django.core.exceptions import ValidationError
# from django.db.models import Q
# import time
#
#
# # 测试树
# def show_genres(request):
#     return render(request, "genres.html", {'genres': Genre.objects.all()})
#
#
# # 登陆
# @csrf_exempt
# def index(request):
#     if request.method == 'GET':  # 如果是get请求
#         menu = SysMenu.objects.filter(parent_id=0).order_by('menu_order')
#         menus = SysMenu.objects.filter(~Q(parent_id=0)).order_by('menu_order')
#         for x in menu:
#             print(x.menu_name)
#             for i in menus:
#                 print(i.menu_name, i.parent_id == x.menu_id)
#         print('----------------------')
#
#         return render(request, 'index.html', {'menu': menu})  # 交给前台
#     else:
#         username = request.POST.get("username")  # 获取前台post 提交的username
#         password = request.POST.get("password")  # 获取前台post 提交的password
#         print(User.objects.filter(username=username, password=password).count())
#         if username == "":
#             response_data = {"info": "请输入账号"}
#             return JsonResponse(response_data)
#         elif password == "":
#             response_data = {"info": "请输入密码"}
#             return JsonResponse(response_data)
#         else:
#             if User.objects.filter(username=username, password=password).count() > 0:
#                 response_data = {"info": "登录成功"}
#                 return JsonResponse(response_data)
#             else:
#                 response_data = {"info": "账号或密码错误"}
#                 return JsonResponse(response_data)
#
#
# #
# # # 注册
# # @csrf_exempt
# # def sign_in(request):
# #     if request.method == 'GET':  # 如果是get请求
# #         path = request.scheme + "://" + request.get_host()  # url
# #         ff_path = request.scheme + "://" + request.get_host() + request.path  # 加方法url
# #         print(path)
# #         print(ff_path)
# #         return render(request, 'login_sign/sign_in.html', {'path': path, 'ff_path': ff_path})  # 交给前台
# #     else:
# #         username = request.POST.get("username")  # 获取前台post 提交的username
# #         password = request.POST.get("password")  # 获取前台post 提交的password
# #         again = request.POST.get("again")  # 获取前台post 提交的重新输入密码
# #         email = request.POST.get("email")
# #         try:
# #             validate_email(email)
# #             print(validate_email(email))
# #             if username == "":
# #                 response_data = {"info": "请输入用户名!"}
# #                 return JsonResponse(response_data)
# #             elif password == "":
# #                 response_data = {"info": "请输入密码！"}
# #                 return JsonResponse(response_data)
# #             elif again != password and again == "":
# #                 response_data = {"info": "请重新确认密码！"}
# #                 return JsonResponse(response_data)
# #             else:
# #                 for x in User.objects.all():  # 循环数据库，判断是否重复
# #                     print(x.username, username)
# #                     if x.username == username:
# #                         response_data = {"info": "你输入的账号已存在"}
# #                         return JsonResponse(response_data)
# #                 else:
# #                     User.objects.create(username=username, password=password, email=email,
# #                                         createby=time.strftime('%Y-%m-%d', time.localtime()))
# #                     response_data = {"info": "成功"}
# #                     return JsonResponse(response_data)
# #         except ValidationError:
# #             response_data = {"info": "请输入正确邮箱"}
# #             return JsonResponse(response_data)
#
#
# # 检查用户名输入
# @csrf_exempt
# def check_username(request):
#     if request.method == 'GET':  # 如果是get请求
#         username = request.GET.get("username")  # 获取前台post 提交的username
#         page = request.GET.get("page")
#         if page == "sign_in":  # 如果是注册页面
#             if username == "":
#                 response_data = {"info": "请输入用户名!"}
#                 return JsonResponse(response_data)
#             elif len(username) < 10:
#                 response_data = {"info": "请输入大于10位的用户名"}
#                 return JsonResponse(response_data)
#             for x in User.objects.all():  # 循环数据库，判断是否重复
#                 if x.username == username:
#                     response_data = {"info": "你输入的账号已存在"}
#                     return JsonResponse(response_data)
#             else:
#                 response_data = {"info": "输入正确"}
#                 return JsonResponse(response_data)
#         else:
#             if request.GET.get("page") == "login":  # 如果是登录页面 用以下判断
#                 if username == "":
#                     response_data = {"info": "请输入用户名!"}
#                     return JsonResponse(response_data)
#                 elif len(username) < 10:
#                     response_data = {"info": "请输入大于10位的用户名"}
#                     return JsonResponse(response_data)
#                 else:
#                     response_data = {"info": "输入正确"}
#                     return JsonResponse(response_data)
#
#
# # 检查密码输入
# @csrf_exempt
# def check_password(request):
#     if request.method == 'POST':  # 如果是get请求
#         password = request.POST.get("password")  # 获取前台post 提交的password
#         print(password)
#         if password == "":
#             response_data = {"info": "请输入密码"}
#             return JsonResponse(response_data)
#         elif len(password) < 10:
#             response_data = {"info": "请输入大于10位的密码"}
#             return JsonResponse(response_data)
#         else:
#             response_data = {"info": "格式正确"}
#             return JsonResponse(response_data)
#     else:
#         response_data = {"info": "请求类型错误"}
#         return JsonResponse(response_data)
#
#
# # 检查邮箱输入
# @csrf_exempt
# def check_email(request):
#     if request.method == 'GET':  # 如果是get请求
#         email = request.GET.get("email")
#         print(email)
#         try:
#             validate_email(email)
#             print(validate_email(email))
#             response_data = {"info": "格式正确"}
#             return JsonResponse(response_data)
#         except ValidationError:
#             response_data = {"info": "请输入正确邮箱"}
#             return JsonResponse(response_data)
#
#
# # 检查重新输入的密码
# @csrf_exempt
# def check_again(request):
#     if request.method == 'POST':  # 如果是get请求
#         password = request.POST.get("password")  # 获取前台post 提交的password
#         again = request.POST.get("again")  # 获取前台post 提交的password1
#         print(password != again)
#         if password == again and again != "":
#             response_data = {"info": "输入正确"}
#             return JsonResponse(response_data)
#         else:
#             response_data = {"info": "请重新确认密码！"}
#             return JsonResponse(response_data)
#     else:
#         response_data = {"info": "请求类型错误"}
#         return JsonResponse(response_data)
